package com.baihui.crm;

import com.baihui.crm.util.BaihuiOptUtil.UTF8PostMethod;
import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class TicketMgr {

	public String getTicket(BaihuiSession baihuiSession,
			TaoBaoSessionInfo taoBaoSessionInfo) throws Exception {
		ObjectInputStream obis = null;
		try {
			String targetURL = null;
			HashMap<String, String> params = null;
			String fileName = "ticket" + taoBaoSessionInfo.getVisitor_id()
					+ ".txt";
			String xmlResp = null;
			HashMap dataMap = null;
			if (!isFileExists(fileName)) {
				return generateTicket(fileName, baihuiSession);
			}
			try {
				FileInputStream fi = new FileInputStream(fileName);
				obis = new ObjectInputStream(fi);
				String ticket = (String) obis.readObject();

				targetURL = "https://crm.baihui.com/crm/private/xml/Contacts/getMyRecords";
				params = new HashMap<String, String>();
				params.put("apikey", baihuiSession.getApiKey());
				params.put("ticket", ticket);
				params.put("newFormat", "2");
				params.put("fromIndex", "1");
				params.put("toIndex", "1");

				xmlResp = connectToCRM(targetURL, params);
				if (xmlResp.indexOf("row") == -1) {
					dataMap = parseXMLIntoMap(xmlResp, "error");
					if (dataMap.get("code") != null
							&& dataMap.get("code").equals("4834")) {
						System.out.println("INVALID TICKET");
						ticket = generateTicket(fileName, baihuiSession);
					}
				}
				return ticket;
			} finally {
				if (obis != null) {
					obis.close();
				}
			}
		} catch (Exception e) {
			throw e;
		}
	}

	public String getToken(String baihuiId, String password) throws Exception {

		if (baihuiId == null || password == null) {
			return null;
		}
		try {
			String targetURL = null;
			String xmlResp = null;
			targetURL = "https://i.baihui.com/apiauthtoken/nb/create";
			PostMethod post = new UTF8PostMethod(targetURL);
			post.setParameter("SCOPE", "ZohoCRM/crmapi");
			post.setParameter("EMAIL_ID", baihuiId);
			post.setParameter("PASSWORD", password);

			HttpClient httpclient = new HttpClient();
			PrintWriter myout = null;
			try {
				int result = httpclient.executeMethod(post);
				// writing the response to a file
				myout = new PrintWriter(new File("response.xml"));
				String reString = post.getResponseBodyAsString();
				if(reString.contains("RESULT=TRUE")){
					reString = reString.substring(reString.indexOf("=") + 1,reString.indexOf("=") + 33);
				}
				// ------------Get response as a string ----------
				return reString;
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			} finally {
				myout.close();
				post.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
public static void main (String[] a){
	String b = "AUTHTOKEN=4698d3d892ac315cd2a4a581c89d9230RESULT=TRUE";
	b = b.substring(b.indexOf("=") + 1,b.indexOf("RESULT"));
	System.out.println(b);
	
}
	private HashMap parseXMLIntoMap(String xmlData, String parentTag)
			throws Exception {
		ByteArrayInputStream bais = null;
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();

			bais = new ByteArrayInputStream(xmlData.getBytes("UTF-8"));
			Document doc = db.parse(new org.xml.sax.InputSource(bais));

			doc.getDocumentElement().normalize();
			System.out.println("Root element of the doc is "
					+ doc.getDocumentElement().getNodeName());

			NodeList parentNodes = doc.getElementsByTagName(parentTag);

			int node_len = parentNodes.getLength();
			NodeList childNodes = null;
			HashMap dataMap = new HashMap();
			for (int i = 0; i < node_len; i++) {
				childNodes = parentNodes.item(i).getChildNodes();
				int child_len = childNodes.getLength();
				HashMap rowMap = new HashMap();
				for (int j = 0; j < child_len; j++) {
					Node node = childNodes.item(j);
					String nodeName = node.getNodeName();
					String nodeValue = getElementValue(node);
					if (parentTag.equals("row")) {
						nodeName = node.getAttributes().getNamedItem("val")
								.getNodeValue();
						rowMap.put(nodeName, nodeValue);
					} else {
						dataMap.put(nodeName, nodeValue);
					}
				}
				if (parentTag.equals("row")) {
					String rowId = parentNodes.item(i).getAttributes()
							.getNamedItem("no").getNodeValue();
					dataMap.put(rowId, rowMap);
				}
			}
			return dataMap;
		} finally {
			if (bais != null) {
				bais.close();
			}
		}
	}

	private String connectToCRM(String targetURL, HashMap<String, String> params)
			throws Exception {
		try {
			PostMethod post = new PostMethod(targetURL);
			for (Map.Entry<String, String> entry : params.entrySet()) {
				String paramName = entry.getKey();
				String paramValue = entry.getValue();
				post.setParameter(paramName, paramValue);
			}

			HttpClient httpclient = new HttpClient();

			try {
				long t1 = System.currentTimeMillis();
				int result = httpclient.executeMethod(post);
				String postResp = post.getResponseBodyAsString();
				return postResp;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				post.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private String getElementValue(Node elem) {
		Node kid;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (kid = elem.getFirstChild(); kid != null; kid = kid
						.getNextSibling()) {
					if (kid.getNodeType() == Node.TEXT_NODE) {
						return kid.getNodeValue();
					}
					if (kid.getNodeType() == Node.CDATA_SECTION_NODE) {
						return kid.getNodeValue();
					}
				}
			}
		}
		return "";
	}

	private boolean isFileExists(String fileName) {
		File file = new File(fileName);
		return file.exists();
	}

	public String generateTicket(String fileName, BaihuiSession baihuiSession)
			throws Exception {
		ObjectOutputStream os = null;
		try {
			String targetURL = "https://i.baihui.com/login";
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("LOGIN_ID", baihuiSession.getUserName());
			params.put("PASSWORD", baihuiSession.getPassword());
			params.put("FROM_AGENT", "true");
			params.put("servicename", BaihuiSession.SERVICENAME);
			String xmlResp = connectToCRM(targetURL, params);
			xmlResp = xmlResp.substring(xmlResp.indexOf("TICKET=") + 7);
			String ticket = xmlResp.substring(0, xmlResp.indexOf("RESULT") - 1);
			os = new ObjectOutputStream(new FileOutputStream(fileName));
			os.writeObject(ticket);
			return ticket;
		} finally {
			if (os != null) {
				os.flush();
				os.close();
			}
		}
	}
}
